var http=require('http');
var fs=require('fs');
var cheerio=require('cheerio');
var request=require('request');
var spa=require('superagent');
var express=require('express');
var eventproxy=require('eventproxy');
var events=require('events');
var eventEmitter=new events.EventEmitter();
var getImg=require('./getImg').getPage;
var rimraf=require('rimraf');
var charset=require('superagent-charset');
var url=require('url');
var async=require('async');
var app=express();




var baseUrl='http://club.autohome.com.cn/jingxuan/104';
var detail_href_list=[];
var sendInfo='';

function getList(url){
    detail_href_list=[];
    spa.get(url).charset('gbk').end(function(err,res){
        res.setEncoding('utf-8');
        if(err){
            console.log('获取mainpage信息失败');
            console.log(err);
            // eventEmitter.emit('error',err);
        };
        console.log('get info succed');
        var $=cheerio.load(res.text);
        
        

       

        $('.pic-box a').each(function(index,ele){
            var $ele=$(ele);

            var tempHref=$ele.attr('href');
            // console.log('ref: '+tempHref);
            detail_href_list.push(tempHref);

        })

         eventEmitter.emit('main_page',res);
         eventEmitter.emit('detail_list',detail_href_list);

        

    })
}

function getDetail(link_lists){
    async.mapLimit(link_lists,3,function(link){
        console.log('传入的link是： '+link);
        spa.get(link)
        .then(function(err,tempRes){
            if(err){
                console.log('get detail failed');
                // console.log(err);
            }
            var detail$=cheerio.load(tempRes.text);

            savedImg(detail$);
            
        })
    })
}






var url='http://club.autohome.com.cn/bbs/thread-c-197-60649403-1.html#pvareaid=102410';


app.get('/',function(req,res,next){

    // res.send(sendInfo)
    getList(baseUrl);

    eventEmitter.on('main_page',function(response){
        res.send(response.text);
    });

    eventEmitter.on('error',function(err){
        res.send('get main page failed');
    });

    eventEmitter.on('detail_list',function(link_lists){
        //  rimraf('./img/**',function(){
        //        console.log('清除img文件夹');
        // });
        fs.mkdir('./img/temp',function(err){
            if(err){console.log('创建img文件夹失败')}
        });

       link_lists.forEach((link,index)=>{
          
           setTimeout(function(){
               console.log(link);
               getImg(link);
           },index*2000)
       })
        
        
       
    })
  
    
});

app.listen(4000,function(){
    console.log('link to 3000 succeed');
})